package com.pan.concurrency.thread;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  每次蜜蜂生产100g的时候， 熊来吃
 * </p>
 *
 * @author kaiji
 * @since 2020/1/25 19:24
 */
public class Works {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        Honeybee honeybee = new Honeybee(list);
        Beer beer = new Beer("熊大", list);

        honeybee.start();
        beer.start();


    }
}


class Honeybee extends Thread {

    private final static int MAX = 100;

    private List<Integer> list;

    public Honeybee(List<Integer> list) {
        this.list = list;
    }


    @Override
    public void run() {
        while (true) {
            synchronized (list) {
                try {
                    if (list.size() >= MAX) {
                        System.out.println("我生产到了100G了， 贼狗熊，你来吃吧！");
                        list.wait();
                    } else {
                        for (int i = 0; i < MAX; i++) {
                        }
                        System.out.println("我在else中生产到了100G了， 贼狗熊，你来吃吧！");
                        list.add(1);
                        list.notifyAll();
                    }
                } catch (Exception e) {}

            }
        }

    }
}


class Beer extends Thread {

    private String username;
    private List<Integer> list;

    public Beer(String username, List<Integer> list) {
        this.username = username;
        this.list = list;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (list) {
                try {
                    if (list.isEmpty()) {
                        list.wait();
                    } else {
                        list.remove(0);
                        System.out.println(username + "： 我吃完了，蜜蜂你来生产吧");
                        list.notifyAll();
                    }
                } catch (InterruptedException e) {}
            }
        }
    }
}
